
/* fishing_forum_mall/frontend/js/mall.js */
/**
 * 钓鱼天堂 - 商城功能脚本
 * 处理商品展示、购物车管理和交易功能
 */

// 页面加载完成后初始化商城功能
document.addEventListener('DOMContentLoaded', function() {
    // 根据当前页面类型初始化不同的功能
    if (window.location.pathname.includes('mall.html')) {
        initializeMallPage();
    } else if (window.location.pathname.includes('cart.html')) {
        initializeCartPage();
    } else if (window.location.pathname.includes('index.html') || window.location.pathname === '/' || window.location.pathname.endsWith('/')) {
        // 首页上可能也有商城部分，初始化首页商城模块
        initializeHomeMallSection();
    }
});

/**
 * 初始化商城页面
 */
function initializeMallPage() {
    console.log('初始化商城页面');
    
    // 加载商品数据
    loadProducts();
    
    // 设置商品筛选功能
    setupProductFiltering();
    
    // 设置排序功能
    setupProductSorting();
    
    // 设置搜索功能
    setupProductSearch();
    
    // 设置购物车侧边栏功能
    setupCartSidebar();
}

/**
 * 初始化购物车页面
 */
function initializeCartPage() {
    console.log('初始化购物车页面');
    
    // 加载购物车数据
    loadCart();
    
    // 设置购物车操作功能
    setupCartOperations();
    
    // 加载推荐商品
    loadRecommendedProducts();
}

/**
 * 初始化首页商城部分
 */
function initializeHomeMallSection() {
    console.log('初始化首页商城模块');
    
    // 在首页加载热门商品预览
    loadFeaturedProductsPreview();
}

/**
 * 加载商品数据
 * @param {string} [category] - 可选的商品分类过滤
 * @param {string} [sortBy] - 可选的排序方式
 * @param {string} [searchTerm] - 可选的搜索关键词
 */
function loadProducts(category, sortBy, searchTerm) {
    // 从localStorage获取商品数据，如果没有则使用默认数据
    let products = JSON.parse(localStorage.getItem('products'));
    
    // 如果没有数据，创建默认商品
    if (!products) {
        products = [
            {
                id: 1,
                name: '专业碳素鱼竿',
                price: 299,
                originalPrice: 399,
                image: 'https://picsum.photos/400/300?rod',
                category: 'rods',
                featured: true,
                hot: true,
                description: '超轻超硬碳素材质，28调节多功能鱼竿，适合各种钓鱼场景，手感舒适，性能稳定。'
            },
            {
                id: 2,
                name: '金属轴承渔轮',
                price: 199,
                originalPrice: 259,
                image: 'https://picsum.photos/400/300?reel',
                category: 'reels',
                featured: true,
                hot: true,
                description: '12+1轴承设计，超强耐磨金属材质，高速比5.2:1，轻松应对大鱼。'
            },
            {
                id: 3,
                name: '仿生软饵套装',
                price: 89,
                originalPrice: 119,
                image: 'https://picsum.photos/400/300?bait',
                category: 'lures',
                featured: true,
                hot: false,
                description: '30款多彩软饵，高度仿真设计，柔软有弹性，气味持久。适合淡水和海水环境。'
            },
            {
                id: 4,
                name: '多功能钓箱',
                price: 359,
                originalPrice: 459,
                image: 'https://picsum.photos/400/300?box',
                category: 'accessories',
                featured: true,
                hot: true,
                description: '高强度工程塑料材质，多层设计，大容量储物空间。内置可调节隔板，防水防潮。'
            },
            {
                id: 5,
                name: '高强度鱼线',
                price: 45,
                originalPrice: 65,
                image: 'https://picsum.photos/400/300?line',
                category: 'lines',
                featured: false,
                hot: true,
                description: '日本进口材料，高强度低延展性，抗磨损抗腐蚀，几乎零记忆力。'
            },
            {
                id: 6,
                name: '专业钓鱼服装套装',
                price: 299,
                originalPrice: 399,
                image: 'https://picsum.photos/400/300?clothing',
                category: 'clothing',
                featured: false,
                hot: true,
                description: '速干透气面料，防晒防水，多口袋设计方便存放小物件。可拆卸袖子和裤腿。'
            },
            {
                id: 7,
                name: '高级碳素短节鱼竿',
                price: 599,
                originalPrice: 799,
                image: 'https://picsum.photos/400/300?rod2',
                category: 'rods',
                featured: false,
                hot: false,
                description: '采用日本东丽碳素纤维，高强度轻量化设计，短节便携，方便携带。'
            },
            {
                id: 8,
                name: '精致鱼钩套装',
                price: 69,
                originalPrice: 99,
                image: 'https://picsum.photos/400/300?hook',
                category: 'hooks',
                featured: false,
                hot: false,
                description: '100枚装，10种规格，高碳钢材质，经久耐用不易生锈。锋利的钩尖，高穿透力。'
            }
        ];
        
        // 保存到localStorage
        localStorage.setItem('products', JSON.stringify(products));
    }
    
    // 过滤商品
    let filteredProducts = products;
    
    // 按分类过滤
    if (category && category !== 'all') {
        filteredProducts = filteredProducts.filter(product => product.category === category);
    }
    
    // 按关键词搜索
    if (searchTerm) {
        searchTerm = searchTerm.toLowerCase();
        filteredProducts = filteredProducts.filter(product => 
            product.name.toLowerCase().includes(searchTerm) || 
            product.description.toLowerCase().includes(searchTerm) ||
            getCategoryName(product.category).toLowerCase().includes(searchTerm)
        );
    }
    
    // 排序商品
    if (sortBy) {
        switch (sortBy) {
            case 'price-asc':
                filteredProducts.sort((a, b) => a.price - b.price);
                break;
            case 'price-desc':
                filteredProducts.sort((a, b) => b.price - a.price);
                break;
            case 'sales':
                // 这里假设有一个sales字段表示销量，实际可能需要根据项目情况调整
                filteredProducts.sort((a, b) => (b.sales || 0) - (a.sales || 0));
                break;
            case 'newest':
                // 这里假设有一个dateAdded字段表示上架日期，实际可能需要根据项目情况调整
                filteredProducts.sort((a, b) => new Date(b.dateAdded || 0) - new Date(a.dateAdded || 0));
                break;
            default:
                // 默认排序，不做改变
                break;
        }
    }
    
    // 渲染不同类型的商品区域
    renderProductSection('featured-products', filteredProducts.filter(p => p.featured), '精选推荐');
    renderProductSection('hot-products', filteredProducts.filter(p => p.hot), '热销商品');
    renderProductSection('all-products', filteredProducts, '全部商品');
}

/**
 * 渲染商品区域
 * @param {string} containerId - 容器元素ID
 * @param {Array} products - 商品数组
 * @param {string} sectionTitle - 区域标题
 */
function renderProductSection(containerId, products, sectionTitle) {
    const container = document.getElementById(containerId);
    if (!container) return;
    
    // 清空容器
    container.innerHTML = '';
    
    // 如果没有商品，显示提示
    if (products.length === 0) {
        container.innerHTML = `
            <div class="col-span-full text-center py-8">
                <div class="text-gray-400 mb-2"><i class="fas fa-search text-4xl"></i></div>
                <p class="text-gray-500">没有找到相关商品</p>
            </div>
        `;
        return;
    }
    
    // 渲染商品
    products.forEach(product => {
        const productCard = document.createElement('div');
        productCard.className = 'bg-white rounded-lg shadow-md overflow-hidden hover:shadow-xl transition duration-300 transform hover:-translate-y-1';
        productCard.innerHTML = `
            <div class="relative">
                <img src="${product.image}" alt="${product.name}" class="w-full h-48 object-cover cursor-pointer product-image" data-id="${product.id}">
                ${product.hot ? '<span class="absolute top-2 right-2 bg-red-500 text-white text-xs font-bold px-2 py-1 rounded">热销</span>' : ''}
            </div>
            <div class="p-4">
                <h3 class="font-bold text-lg mb-1 cursor-pointer product-name" data-id="${product.id}">${product.name}</h3>
                <div class="flex items-center mb-2">
                    <div class="flex text-yellow-400 text-sm mr-1">
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star-half-alt"></i>
                    </div>
                    <span class="text-xs text-gray-500">(${Math.floor(Math.random() * 200) + 50})</span>
                </div>
                <div class="flex justify-between items-center">
                    <div>
                        <span class="text-red-600 font-bold">¥${product.price.toFixed(2)}</span>
                        <span class="text-gray-500 text-sm line-through ml-1">¥${product.originalPrice.toFixed(2)}</span>
                    </div>
                    <button class="add-to-cart bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded text-sm transition duration-300" data-id="${product.id}">
                        加入购物车
                    </button>
                </div>
            </div>
        `;
        container.appendChild(productCard);
    });
    
    // 添加事件监听器
    setupProductCardListeners();
}

/**
 * 为商品卡片添加事件监听器
 */
function setupProductCardListeners() {
    // 商品图片点击事件
    const productImages = document.querySelectorAll('.product-image');
    productImages.forEach(image => {
        image.addEventListener('click', function() {
            const productId = parseInt(this.getAttribute('data-id'));
            showProductModal(productId);
        });
    });
    
    // 商品名称点击事件
    const productNames = document.querySelectorAll('.product-name');
    productNames.forEach(name => {
        name.addEventListener('click', function() {
            const productId = parseInt(this.getAttribute('data-id'));
            showProductModal(productId);
        });
    });
    
    // 添加到购物车按钮点击事件
    const addToCartButtons = document.querySelectorAll('.add-to-cart');
    addToCartButtons.forEach(button => {
        button.addEventListener('click', function() {
            const productId = parseInt(this.getAttribute('data-id'));
            addToCart(productId, 1);
        });
    });
}

/**
 * 显示商品详情模态框
 * @param {number} productId - 商品ID
 */
function showProductModal(productId) {
    // 获取商品数据
    const products = JSON.parse(localStorage.getItem('products') || '[]');
    const product = products.find(p => p.id === productId);
    
    if (!product) return;
    
    // 获取模态框元素
    const modal = document.getElementById('product-modal');
    const modalImage = document.getElementById('modal-product-image');
    const modalName = document.getElementById('modal-product-name');
    const modalPrice = document.getElementById('modal-product-price');
    const modalDesc = document.getElementById('modal-product-desc');
    const addToCartBtn = document.getElementById('add-to-cart-modal');
    
    // 设置模态框内容
    if (modalImage) modalImage.src = product.image;
    if (modalName) modalName.textContent = product.name;
    if (modalPrice) modalPrice.textContent = `¥${product.price.toFixed(2)}`;
    if (modalDesc) modalDesc.textContent = product.description;
    if (addToCartBtn) addToCartBtn.setAttribute('data-id', product.id);
    
    // 重置数量输入框
    const quantityInput = document.getElementById('product-quantity');
    if (quantityInput) quantityInput.value = 1;
    
    // 显示模态框
    if (modal) modal.classList.remove('hidden');
}

/**
 * 添加商品到购物车
 * @param {number} productId - 商品ID
 * @param {number} quantity - 数量
 */
function addToCart(productId, quantity) {
    // 获取商品数据
    const products = JSON.parse(localStorage.getItem('products') || '[]');
    const product = products.find(p => p.id === productId);
    
    if (!product) return;
    
    // 获取购物车数据
    let cart = JSON.parse(localStorage.getItem('cart') || '[]');
    
    // 检查商品是否已在购物车中
    const existingItem = cart.find(item => item.id === productId);
    
    if (existingItem) {
        // 更新数量
        existingItem.quantity += parseInt(quantity);
    } else {
        // 添加新商品
        cart.push({
            id: product.id,
            name: product.name,
            price: product.price,
            image: product.image,
            quantity: parseInt(quantity)
        });
    }
    
    // 保存购物车
    localStorage.setItem('cart', JSON.stringify(cart));
    
    // 更新购物车计数
    updateCartCount();
    
    // 更新购物车侧边栏
    updateCartSidebar();
    
    // 显示通知
    showNotification('商品已添加到购物车');
    
    // 关闭商品详情模态框
    const modal = document.getElementById('product-modal');
    if (modal) modal.classList.add('hidden');
}

/**
 * 更新购物车数量显示
 */
function updateCartCount() {
    const cart = JSON.parse(localStorage.getItem('cart') || '[]');
    const cartCount = document.getElementById('cart-count');
    
    if (cartCount) {
        cartCount.textContent = cart.length;
    }
}

/**
 * 更新购物车侧边栏
 */
function updateCartSidebar() {
    const cartItems = document.getElementById('cart-items');
    const cartTotal = document.getElementById('cart-total');
    
    if (!cartItems || !cartTotal) return;
    
    const cart = JSON.parse(localStorage.getItem('cart') || '[]');
    
    if (cart.length === 0) {
        // 购物车为空
        cartItems.innerHTML = `
            <div class="text-center text-gray-500 py-10">
                <i class="fas fa-shopping-cart text-5xl mb-3"></i>
                <p>您的购物车是空的</p>
            </div>
        `;
        cartTotal.textContent = '¥0.00';
    } else {
        // 显示购物车商品
        cartItems.innerHTML = '';
        let total = 0;
        
        cart.forEach(item => {
            const itemTotal = item.price * item.quantity;
            total += itemTotal;
            
            const itemElement = document.createElement('div');
            itemElement.className = 'flex items-start border-b border-gray-200 pb-4 mb-4';
            itemElement.innerHTML = `
                <img src="${item.image}" alt="${item.name}" class="w-16 h-16 object-cover rounded mr-3">
                <div class="flex-1">
                    <h4 class="font-medium">${item.name}</h4>
                    <div class="flex justify-between mt-1">
                        <span class="text-gray-600">¥${item.price.toFixed(2)} × ${item.quantity}</span>
                        <span class="font-medium">¥${itemTotal.toFixed(2)}</span>
                    </div>
                </div>
                <button class="remove-from-cart ml-2 text-gray-400 hover:text-red-500" data-id="${item.id}">
                    <i class="fas fa-trash"></i>
                </button>
            `;
            cartItems.appendChild(itemElement);
        });
        
        // 更新总价
        cartTotal.textContent = `¥${total.toFixed(2)}`;
        
        // 添加移除商品的事件监听器
        const removeButtons = cartItems.querySelectorAll('.remove-from-cart');
        removeButtons.forEach(button => {
            button.addEventListener('click', function() {
                removeFromCart(parseInt(this.getAttribute('data-id')));
            });
        });
    }
}

/**
 * 从购物车中移除商品
 * @param {number} productId - 商品ID
 */
function removeFromCart(productId) {
    // 获取购物车数据
    let cart = JSON.parse(localStorage.getItem('cart') || '[]');
    
    // 过滤掉要移除的商品
    cart = cart.filter(item => item.id !== productId);
    
    // 保存购物车
    localStorage.setItem('cart', JSON.stringify(cart));
    
    // 更新购物车计数
    updateCartCount();
    
    // 更新购物车侧边栏
    updateCartSidebar();
    
    // 如果在购物车页面，重新加载购物车内容
    if (window.location.pathname.includes('cart.html')) {
        loadCart();
    }
    
    // 显示通知
    showNotification('商品已从购物车移除');
}

/**
 * 加载购物车页面内容
 */
function loadCart() {
    const cart = JSON.parse(localStorage.getItem('cart') || '[]');
    const emptyCart = document.getElementById('empty-cart');
    const cartContent = document.getElementById('cart-content');
    const cartItems = document.getElementById('cart-items');
    const cartTotal = document.getElementById('cart-total');
    
    if (!emptyCart || !cartContent || !cartItems || !cartTotal) return;
    
    if (cart.length === 0) {
        // 购物车为空
        emptyCart.classList.remove('hidden');
        cartContent.classList.add('hidden');
    } else {
        // 购物车有商品
        emptyCart.classList.add('hidden');
        cartContent.classList.remove('hidden');
        
        // 清空商品列表
        cartItems.innerHTML = '';
        
        // 计算总价
        let total = 0;
        
        // 渲染购物车商品
        cart.forEach(item => {
            const itemTotal = item.price * item.quantity;
            total += itemTotal;
            
            const itemElement = document.createElement('div');
            itemElement.className = 'flex flex-col md:flex-row items-center p-4 md:py-6';
            itemElement.innerHTML = `
                <div class="w-full md:w-2/5 flex items-center mb-4 md:mb-0">
                    <img src="${item.image}" alt="${item.name}" class="w-16 h-16 object-cover rounded mr-4">
                    <div>
                        <h3 class="font-medium">${item.name}</h3>
                        <p class="text-sm text-gray-500">规格：标准版</p>
                    </div>
                </div>
                <div class="w-full md:w-1/5 text-center mb-4 md:mb-0">
                    <span class="text-red-600 font-medium">¥${item.price.toFixed(2)}</span>
                </div>
                <div class="w-full md:w-1/5 flex items-center justify-center mb-4 md:mb-0">
                    <div class="flex items-center">
                        <button class="quantity-btn decrease-btn px-3 py-1 border border-gray-300 rounded-l-md hover:bg-gray-100" data-id="${item.id}">-</button>
                        <input type="number" value="${item.quantity}" min="1" class="item-quantity w-12 px-2 py-1 border-t border-b border-gray-300 text-center focus:outline-none" data-id="${item.id}" readonly>
                        <button class="quantity-btn increase-btn px-3 py-1 border border-gray-300 rounded-r-md hover:bg-gray-100" data-id="${item.id}">+</button>
                    </div>
                </div>
                <div class="w-full md:w-1/5 flex items-center justify-between md:justify-center">
                    <span class="text-red-600 font-bold md:mr-4">¥${itemTotal.toFixed(2)}</span>
                    <button class="remove-item text-gray-400 hover:text-red-500" data-id="${item.id}">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            `;
            cartItems.appendChild(itemElement);
        });
        
        // 更新总价
        cartTotal.textContent = `¥${total.toFixed(2)}`;
        
        // 添加购物车操作事件
        setupCartItemEvents();
    }
}

/**
 * 设置购物车商品的交互事件
 */
function setupCartItemEvents() {
    // 减少数量按钮
    const decreaseButtons = document.querySelectorAll('.decrease-btn');
    decreaseButtons.forEach(button => {
        button.addEventListener('click', function() {
            const productId = parseInt(this.getAttribute('data-id'));
            updateCartItemQuantity(productId, -1);
        });
    });
    
    // 增加数量按钮
    const increaseButtons = document.querySelectorAll('.increase-btn');
    increaseButtons.forEach(button => {
        button.addEventListener('click', function() {
            const productId = parseInt(this.getAttribute('data-id'));
            updateCartItemQuantity(productId, 1);
        });
    });
    
    // 移除商品按钮
    const removeButtons = document.querySelectorAll('.remove-item');
    removeButtons.forEach(button => {
        button.addEventListener('click', function() {
            const productId = parseInt(this.getAttribute('data-id'));
            removeFromCart(productId);
        });
    });
}

/**
 * 更新购物车商品数量
 * @param {number} productId - 商品ID
 * @param {number} change - 数量变化值
 */
function updateCartItemQuantity(productId, change) {
    // 获取购物车数据
    let cart = JSON.parse(localStorage.getItem('cart') || '[]');
    
    // 查找商品
    const item = cart.find(item => item.id === productId);
    if (!item) return;
    
    // 更新数量，确保不小于1
    item.quantity = Math.max(1, item.quantity + change);
    
    // 保存购物车
    localStorage.setItem('cart', JSON.stringify(cart));
    
    // 重新加载购物车内容
    loadCart();
}

/**
 * 设置商品筛选功能
 */
function setupProductFiltering() {
    const categoryButtons = document.querySelectorAll('.category-btn');
    if (!categoryButtons.length) return;
    
    categoryButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();
            
            // 移除所有按钮的活跃状态
            categoryButtons.forEach(btn => {
                btn.classList.remove('active', 'bg-blue-500', 'text-white');
                btn.classList.add('bg-gray-200', 'text-gray-700');
            });
            
            // 添加当前按钮的活跃状态
            this.classList.add('active', 'bg-blue-500', 'text-white');
            this.classList.remove('bg-gray-200', 'text-gray-700');
            
            // 获取分类值
            const category = this.getAttribute('data-category');
            
            // 重新加载商品
            loadProducts(category);
        });
    });
}

/**
 * 设置商品排序功能
 */
function setupProductSorting() {
    const sortSelect = document.getElementById('sort-order');
    if (!sortSelect) return;
    
    sortSelect.addEventListener('change', function() {
        const category = document.querySelector('.category-btn.active')?.getAttribute('data-category') || 'all';
        const searchTerm = document.getElementById('search-products')?.value.trim() || '';
        
        // 重新加载商品
        loadProducts(category, this.value, searchTerm);
    });
}

/**
 * 设置商品搜索功能
 */
function setupProductSearch() {
    const searchInput = document.getElementById('search-products');
    const searchBtn = document.getElementById('search-btn');
    
    if (!searchInput || !searchBtn) return;
    
    // 搜索按钮点击事件
    searchBtn.addEventListener('click', function() {
        const category = document.querySelector('.category-btn.active')?.getAttribute('data-category') || 'all';
        const sortBy = document.getElementById('sort-order')?.value || 'default';
        const searchTerm = searchInput.value.trim();
        
        // 重新加载商品
        loadProducts(category, sortBy, searchTerm);
    });
    
    // 回车键搜索
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            searchBtn.click();
        }
    });
}

/**
 * 设置购物车侧边栏功能
 */
function setupCartSidebar() {
    const cartIcon = document.querySelector('a[href="cart.html"]');
    const cartSidebar = document.getElementById('cart-sidebar');
    const closeCartBtn = document.getElementById('close-cart-sidebar');
    
    if (!cartIcon || !cartSidebar || !closeCartBtn) return;
    
    // 点击购物车图标显示侧边栏
    cartIcon.addEventListener('click', function(e) {
        if (window.innerWidth >= 768) { // 只在平板和桌面端显示侧边栏
            e.preventDefault();
            updateCartSidebar();
            cartSidebar.classList.remove('translate-x-full');
        }
    });
    
    // 点击关闭按钮
    closeCartBtn.addEventListener('click', function() {
        cartSidebar.classList.add('translate-x-full');
    });
}

/**
 * 设置购物车页面操作功能
 */
function setupCartOperations() {
    // 清空购物车按钮
    const clearCartBtn = document.getElementById('clear-cart');
    if (clearCartBtn) {
        clearCartBtn.addEventListener('click', function() {
            // 显示确认对话框
            const confirmModal = document.getElementById('confirm-clear-modal');
            if (confirmModal) confirmModal.classList.remove('hidden');
        });
    }
    
    // 确认清空购物车
    const confirmClearBtn = document.getElementById('confirm-clear');
    if (confirmClearBtn) {
        confirmClearBtn.addEventListener('click', function() {
            // 清空购物车
            localStorage.setItem('cart', '[]');
            
            // 更新购物车计数和内容
            updateCartCount();
            loadCart();
            
            // 隐藏确认对话框
            const confirmModal = document.getElementById('confirm-clear-modal');
            if (confirmModal) confirmModal.classList.add('hidden');
            
            // 显示通知
            showNotification('购物车已清空');
        });
    }
    
    // 取消清空购物车
    const cancelClearBtn = document.getElementById('cancel-clear');
    if (cancelClearBtn) {
        cancelClearBtn.addEventListener('click', function() {
            const confirmModal = document.getElementById('confirm-clear-modal');
            if (confirmModal) confirmModal.classList.add('hidden');
        });
    }
    
    // 结算按钮
    const checkoutBtn = document.getElementById('checkout-btn');
    if (checkoutBtn) {
        checkoutBtn.addEventListener('click', function() {
            // 显示结算对话框
            const checkoutModal = document.getElementById('checkout-modal');
            if (checkoutModal) checkoutModal.classList.remove('hidden');
        });
    }
    
    // 关闭结算对话框
    const closeCheckoutModalBtn = document.getElementById('close-checkout-modal');
    if (closeCheckoutModalBtn) {
        closeCheckoutModalBtn.addEventListener('click', function() {
            const checkoutModal = document.getElementById('checkout-modal');
            if (checkoutModal) checkoutModal.classList.add('hidden');
        });
    }
}

/**
 * 加载首页热门商品预览
 */
function loadFeaturedProductsPreview() {
    const products = JSON.parse(localStorage.getItem('products') || '[]');
    const featuredProducts = products.filter(p => p.featured);
    
    // 渲染到首页热门商品容器
    const container = document.getElementById('featured-products');
    if (!container) return;
    
    container.innerHTML = '';
    
    featuredProducts.forEach(product => {
        const productElement = document.createElement('div');
        productElement.className = 'bg-white rounded-lg shadow-md overflow-hidden hover:shadow-xl transition duration-300 transform hover:-translate-y-1';
        productElement.innerHTML = `
            <div class="relative">
                <img src="${product.image}" alt="${product.name}" class="w-full h-48 object-cover">
                ${product.hot ? '<span class="absolute top-2 right-2 bg-red-500 text-white text-xs font-bold px-2 py-1 rounded">热销</span>' : ''}
            </div>
            <div class="p-4">
                <h3 class="font-bold text-lg mb-1">${product.name}</h3>
                <div class="flex items-center mb-2">
                    <div class="flex text-yellow-400 text-sm mr-1">
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star-half-alt"></i>
                    </div>
                    <span class="text-xs text-gray-500">(${Math.floor(Math.random() * 200) + 50})</span>
                </div>
                <div class="flex justify-between items-center">
                    <div>
                        <span class="text-red-600 font-bold">¥${product.price.toFixed(2)}</span>
                        <span class="text-gray-500 text-sm line-through ml-1">¥${product.originalPrice.toFixed(2)}</span>
                    </div>
                    <button class="add-to-cart bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded text-sm transition duration-300" data-id="${product.id}">
                        加入购物车
                    </button>
                </div>
            </div>
        `;
        container.appendChild(productElement);
    });
    
    // 添加加入购物车功能
    const addToCartButtons = container.querySelectorAll('.add-to-cart');
    addToCartButtons.forEach(button => {
        button.addEventListener('click', function() {
            const productId = parseInt(this.getAttribute('data-id'));
            addToCart(productId, 1);
        });
    });
}

/**
 * 加载推荐商品
 */
function loadRecommendedProducts() {
    const products = JSON.parse(localStorage.getItem('products') || '[]');
    
    // 随机选择4个商品作为推荐
    const shuffledProducts = products.sort(() => 0.5 - Math.random());
    const recommendedProducts = shuffledProducts.slice(0, 4);
    
    // 渲染到推荐商品容器
    const container = document.getElementById('recommended-products');
    if (!container) return;
    
    container.innerHTML = '';
    
    recommendedProducts.forEach(product => {
        const productElement = document.createElement('div');
        productElement.className = 'bg-white rounded-lg shadow-md overflow-hidden hover:shadow-xl transition duration-300 transform hover:-translate-y-1';
        productElement.innerHTML = `
            <div class="relative">
                <img src="${product.image}" alt="${product.name}" class="w-full h-48 object-cover">
            </div>
            <div class="p-4">
                <h3 class="font-bold text-lg mb-1">${product.name}</h3>
                <div class="flex items-center mb-2">
                    <div class="flex text-yellow-400 text-sm mr-1">
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star"></i>
                        <i class="fas fa-star-half-alt"></i>
                    </div>
                    <span class="text-xs text-gray-500">(${Math.floor(Math.random() * 200) + 50})</span>
                </div>
                <div class="flex justify-between items-center">
                    <div>
                        <span class="text-red-600 font-bold">¥${product.price.toFixed(2)}</span>
                        <span class="text-gray-500 text-sm line-through ml-1">¥${product.originalPrice.toFixed(2)}</span>
                    </div>
                    <button class="add-to-cart bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded text-sm transition duration-300" data-id="${product.id}">
                        加入购物车
                    </button>
                </div>
            </div>
        `;
        container.appendChild(productElement);
    });
    
    // 添加加入购物车功能
    const addToCartButtons = container.querySelectorAll('.add-to-cart');
    addToCartButtons.forEach(button => {
        button.addEventListener('click', function() {
            const productId = parseInt(this.getAttribute('data-id'));
            addToCart(productId, 1);
        });
    });
}

/**
 * 获取商品分类名称
 * @param {string} categoryId - 分类ID
 * @returns {string} 分类名称
 */
function getCategoryName(categoryId) {
    const categoryMap = {
        'rods': '鱼竿',
        'reels': '渔轮',
        'lines': '鱼线',
        'hooks': '鱼钩',
        'lures': '假饵',
        'accessories': '配件',
        'clothing': '钓鱼服装'
    };
    
    return categoryMap[categoryId] || categoryId;
}

/**
 * 显示通知
 * @param {string} message - 通知消息
 */
function showNotification(message) {
    const notification = document.getElementById('notification');
    if (!notification) return;
    
    notification.textContent = message;
    notification.classList.remove('hidden', 'translate-y-20', 'opacity-0');
    
    setTimeout(() => {
        notification.classList.add('translate-y-20', 'opacity-0');
        setTimeout(() => {
            notification.classList.add('hidden');
        }, 300);
    }, 2000);
}
